/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import { Component, ReactNode } from 'react';
import { AreaUtils } from '../../utils/AreaUtils';
import { topButtons, gridImages, bottomButtons } from '../../common/ResPath';
import { AvoidAreaType } from '../../common/windowCommon';
import './index.css';

const TAG = 'GAMEPAGE:';

export default class Game extends Component {
  state = {
    needChangeView: false,
    rowNum: 4,
    columnNum: 8,
    gridItems: gridImages,
    margins: {
      leftTopMargin: 0,
      rightTopMargin: 0,
      leftBottomMargin: 0,
      rightBottomMargin: 0,
      leftCenterMargin: 0,
      rightCenterMargin: 0
    },
    topMargin: AreaUtils.getInstance().getTopMargin(),
    bottomMargin: AreaUtils.getInstance().getBottomMargin(),
  };

  reCulcAvoidArea(): void {
    AreaUtils.getAvoidAreaLocation().then((res) => {
      AreaUtils.getInstance().setAvoidValue(res.areaLocation, res.marginValue);
      const margins = AreaUtils.getAllMargin();
      const needChangeView = AreaUtils.checkIfNeedChangeView();
      this.setState({
        margins: margins,
        needChangeView: needChangeView
      });
    });
  };

  calculateGridItemNum = (): void => {
    const game = document.querySelector('.game');
    if (game) {
      const itemSize = 72; // 每个 grid-item 的大小
      const margin = 6; // 每个 grid-item 的外边距
      const topHeight = 76;
      const bottomHeight = 63;
      const sideWidth = 4;

      //计算容器宽高
      const gridWidth = Number(getComputedStyle(game).getPropertyValue('width').replace('px', ''));
      const gridHeight = Number(getComputedStyle(game).getPropertyValue('height').replace('px', ''));

      //计算左右边距和容器可用高度
      let leftMargin; 
      let rightMargin;
      let availableHeight = gridHeight - topHeight;
      if (this.state.needChangeView) {
        leftMargin = this.state.margins.leftBottomMargin || this.state.margins.leftCenterMargin + sideWidth;
        rightMargin = this.state.margins.rightBottomMargin || this.state.margins.rightCenterMargin + sideWidth;
        availableHeight -= bottomHeight;
      } else {
        leftMargin = this.state.margins.leftCenterMargin + sideWidth;
        rightMargin = this.state.margins.rightCenterMargin + sideWidth;
      }

      //计算网格数量
      const rowNum = Math.floor((gridWidth - leftMargin - rightMargin) / (itemSize + 2 * margin));
      const columnNum = Math.round(availableHeight / (itemSize + 2 * margin));
      this.setState({
        rowNum: rowNum,
        columnNum: columnNum
      });

      let totalNum = rowNum * columnNum;
      const randomItems = [];
      for (let i = 0; i < totalNum; i++) {
        const randomIndex = Math.floor(Math.random() * gridImages.length);
        randomItems.push(gridImages[randomIndex]);
      }
      this.setState({ gridItems: randomItems });
    }
  };

  handleStatusBarChange = (event: any): void => {
    console.debug(TAG, `statusBarChange data is ${JSON.stringify(event.detail)}`);
    const data = event.detail;
    const areaType = data.type;
    this.reCulcAvoidArea();
    if (areaType === AvoidAreaType.TYPE_SYSTEM) {
      this.setState({ topMargin: AreaUtils.px2vp(data.area.topRect.height) });
      AreaUtils.getInstance().setTopMargin(this.state.topMargin);
    }
    if (areaType === AvoidAreaType.TYPE_CUTOUT) {
      this.calculateGridItemNum();
    }
    if (areaType === AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
      this.setState({ bottomMargin: AreaUtils.px2vp(data.area.bottomRect.height) });
      AreaUtils.getInstance().setBottomMargin(this.state.bottomMargin);
    }
  };

  componentDidMount(): void {
    this.reCulcAvoidArea();
    this.calculateGridItemNum();
    window.addEventListener('resize', this.calculateGridItemNum);
    window.addEventListener('statusBarChange', this.handleStatusBarChange);
  }

  componentWillUnmount(): void {
    window.removeEventListener('resize', this.calculateGridItemNum);
    window.removeEventListener('statusBarChange', this.handleStatusBarChange);
  }

  render(): ReactNode {
    return (
      <div className='game'>
        {/* 按钮组 */}
        <div className='button-group' style={{
          marginTop: `${this.state.topMargin + 8}px`,
          marginLeft: `${(this.state.topMargin ? 0 : this.state.margins.leftTopMargin) + 16}px`,
          marginRight: `${(this.state.topMargin ? 0 : this.state.margins.rightTopMargin) + 16}px`
        }}>
          {/* 顶部按钮 */}
          <div className='top-buttons' style={{ width: !this.state.needChangeView ? '100%' : 'auto' }}>
            <img src={topButtons[0]} alt='' className='button-image' />
            <div className='center-blank' style={{ display: this.state.needChangeView ? 'block' : 'none' }}></div>
            <img src={require('../../assets/stars.png')} alt='' className='image-star'
              style={{ height: '54px', display: this.state.rowNum > 6 && !this.state.needChangeView ? 'block' : 'none' }} />
            <img src={topButtons[1]} alt='' className='button-image' />
          </div>
          {/* 中间空白填充 */}
          <div className='center-blank' style={{ display: this.state.needChangeView ? 'block' : 'none' }}></div>
          {/* 侧边按钮 */}
          {this.state.needChangeView &&
            <div className='bottom-buttons'>
              <img src={bottomButtons[0]} alt='' className='button-image' />
              <img src={bottomButtons[1]} alt='' className='button-image' />
              <img src={bottomButtons[2]} alt='' className='button-image' />
            </div>}
        </div>

        {/* 中间网格容器 */}
        <div className='grid-container' style={{
          paddingLeft: this.state.needChangeView ? `${this.state.margins.leftBottomMargin || this.state.margins.leftCenterMargin + 16}px` : `${this.state.margins.leftCenterMargin + 16}px`,
          paddingRight: this.state.needChangeView ? `${this.state.margins.rightBottomMargin || this.state.margins.rightCenterMargin + 16}px` : `${this.state.margins.rightCenterMargin + 16}px`,
          gridTemplateColumns: `repeat(${this.state.rowNum}, minmax(68px, 72px))`,
          gridAutoRows: 'minmax(68px, 72px)'
        }}>
          {this.state.gridItems.map((item, index) =>
            <div className='grid-item' key={index}>
              <img src={item} alt='' className='grid-image' />
            </div>
          )}
        </div>

        {/* 底部按钮 */}
        {!this.state.needChangeView && <div className='bottom-buttons' style={{
          marginLeft: `${(this.state.bottomMargin ? 0 : this.state.margins.leftBottomMargin) + 16}px`,
          marginRight: `${(this.state.bottomMargin ? 0 : this.state.margins.rightBottomMargin) + 16}px`,
          marginBottom: `${this.state.bottomMargin + 12}px`
        }}>
          <img src={bottomButtons[0]} alt='' className='button-image' />
          <div className='bottomRight-buttons'>
            <img src={bottomButtons[1]} alt='' className='button-image' />
            <img src={bottomButtons[2]} alt='' className='button-image' />
          </div>
        </div>}
      </div>
    );
  }
}
